//
//  CLSyndromeController.m
//  CareLink
//
//  Created by whong7 on 16/8/19.
//  Copyright © 2016年 Seven Team. All rights reserved.
//

#import "CLSyndromeController.h"
#import "CLDiseaseStyleModel.h"
#import "CLSyndromeModel.h"
#import "CLSyndromeCell.h"
//设定cellid
static NSString *cellid = @"syndrome_cell";

@interface CLSyndromeController ()

//网络请求管理器
@property(nonatomic,strong)CLNetworkManager *networkManager;
//数据数组
@property(nonatomic,strong)NSArray *dataArray;
//返回的模型
@property(nonatomic,strong)CLSyndromeModel *returnModel;
//并发症数组
@property(nonatomic,strong)NSMutableDictionary *SyndromeDict;

@end

@implementation CLSyndromeController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadData];
}


-(void)setupUI
{
    //view布局
    self.view.backgroundColor = [UIColor colorWithHex:0xF5F5F5];

    //注册xib单元格
    UINib *nib = [UINib nibWithNibName:@"CLSyndromeCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:cellid];
    //去掉多余的线
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView setTableFooterView:v];
    
    //选定
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleDone  target:self action:@selector(selectedOk)];
    
    
    NSLog(@"%@",self.totalDetails);
#warning mark ---------设置返回按钮文字为空
    // 设置返回的按钮的文字为空
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    
    __weak typeof(self) weakSelf = self;
    //MARK: 下拉刷新
    self.tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //请求下拉数据
        [weakSelf loadData];
        
    }];
    

    
    
    
}
//MARK:点击确定，回传数据
-(void)selectedOk
{
    
    if (self.inputCompeletionBlock != nil) {
        self.inputCompeletionBlock(self.SyndromeDict.copy);
    }

    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 加载数据 并给 模型数组 赋值
-(void)loadData
{
    //选择科目内部数据
    NSString *ci2_id = self.totalDetails[@"ci2_id"];
    
    NSString *url = @"http://iosapi.itcast.cn/complicationList.json.php";
    NSDictionary *paramDic = @{@"login_token":@"985c96ce43bb5ef69de3e1ad8afaa83f",@"page":@(1),@"page_size":@(15),@"ci2_id":ci2_id};
    
    [self.networkManager POST:url parameters:paramDic success:^(id responseObject) {
        
        NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        //得到二级病类的模型数组
        self.dataArray = [NSArray yy_modelArrayWithClass:[CLSyndromeModel class] json:[response objectForKey:@"data"]].copy;
        if (self.dataArray.count == 0) {
            
            [SVProgressHUD showImage:[UIImage imageNamed:@"warning"] status:@"暂无可选并发症"];
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];//只有none是可以继续用户交互的
            //延时
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });

            
        }
        
        // 结束更新刷新
        [self.tableView.mj_header endRefreshing];
        NSLog(@"%@",self.dataArray);
        [self.tableView reloadData];
        
    }
    failure:^(NSError *error)
     {
          NSLog(@"%@",error);
         [SVProgressHUD showImage:[UIImage imageNamed:@"warning"] status:@"网络加载失败"];
         [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];//只有none是可以继续用户交互的
         // 结束刷新
         [self.tableView.mj_header endRefreshing];
         //延时
         dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             [SVProgressHUD dismiss];
         });

    }];
    
    
    
}


#pragma mark - 数据源方法

//某一组有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
//cell的内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //取当前模型
    CLSyndromeModel *model = self.dataArray[indexPath.row];
    
    //取缓存池找
    CLSyndromeCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid forIndexPath:indexPath];
    cell.nameLabel.text = model.complication_name;
    cell.nameLabel.textColor = [UIColor colorWithHex:0x666666];
    cell.nameLabel.font = [UIFont systemFontOfSize:14];
    //去掉cell的颜色
    cell.backgroundColor = [UIColor clearColor];

    
    //二次进入的时候 如果 选中过，对应的button 高亮
    NSArray *array = self.totalDetails[@"complications"];
    //如果包含指定元素
    if ([array containsObject:model.complication_name]) {
        cell.clickButton.highlighted = YES;
        [self.SyndromeDict setValue:model.complication_name forKey:[NSString stringWithFormat:@"%ld",indexPath.row]];
    }
    
    return cell;
}


#pragma mark - 代理方法
//被选中的时候 运行
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    self.returnModel = self.dataArray[indexPath.row];
    // 这句话的意思 就是让table是否以动画的形式 取消indexPath这个位置的背景色
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //取到对应的一个的cell
    CLSyndromeCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if (cell.clickButton.highlighted != YES) {
        cell.clickButton.highlighted = YES;
        [self.SyndromeDict setValue:self.returnModel.complication_name forKey:[NSString stringWithFormat:@"%ld",indexPath.row]];
    }
    else
    {
        cell.clickButton.highlighted = NO;
        [self.SyndromeDict removeObjectForKey:[NSString stringWithFormat:@"%ld",indexPath.row]];
        
    }
    
    
}






#pragma mark - 懒加载

- (CLNetworkManager *)networkManager {
    
    if (_networkManager == nil) {
        
        _networkManager = [CLNetworkManager sharedManager];
        
    }
    return _networkManager;
    
    
}

-(NSArray *)dataArray
{
    if (_dataArray == nil) {
        
        _dataArray = [NSArray array];
        
    }
    return _dataArray;
}

-(NSMutableDictionary *)SyndromeDict
{
    if (_SyndromeDict == nil) {
        _SyndromeDict = [NSMutableDictionary dictionary];
    }
    
    return _SyndromeDict;

}



#pragma mark - 取消系统线

- (void)viewDidLayoutSubviews
{ if([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
{ [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)]; }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])
    { [self.tableView setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)]; } }

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{ if ([cell respondsToSelector:@selector(setSeparatorInset:)])
{
    [cell setSeparatorInset:UIEdgeInsetsZero];
}
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)dealloc
{
    // controller 销毁的时候，取消所有正在下载的线程
    [self.networkManager cancelOperations];
    NSLog(@"我去了");
}
@end
